package top.lingkang.authoritypro.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import top.lingkang.authoritypro.config.handler.CustomLoginUrlAuthenticationEntryPoint;
import top.lingkang.authoritypro.config.handler.LoginFialHandler;
import top.lingkang.authoritypro.config.handler.LoginSuccessHandler;

/**
 * @author lingkang
 * Created by 2021/12/14
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //注入我们加密的方式，spring5+以上必须要加密密码，这是官网推荐的加密方式，也可选择MD5
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //授权规则，除了要授权的，其他所有人能访问
//        http.authorizeRequests()
//                .antMatchers("/vip1/**").hasAnyRole("vip1")
//                .antMatchers("/vip2/**").hasAnyRole("vip2")
//                .antMatchers("/vip3/**").hasAnyRole("vip3")
//                .anyRequest().permitAll(); //其他页面所有人能访问
        http.authorizeRequests()
                .antMatchers("/auth/login", "/assets/**").permitAll()
                .anyRequest().authenticated();

        //启动登陆页面
        //定制登陆页面，表单提交的路径loginProcessingUrl
        http.formLogin().loginPage("/auth/login").loginProcessingUrl("/login")
                .successHandler(new LoginSuccessHandler())
                .failureHandler(new LoginFialHandler());

        //注销功能 ,跳回首页
        //关闭跨域认证请求，否则你需要post来注销
        http.logout().logoutSuccessUrl("/")
                .and().csrf().disable();

        //开启记住我功能，表单提交remember的参数
        //http.rememberMe().rememberMeParameter("remember");

        //允许在frame上显示
        http.headers().frameOptions().disable();

        //自定义未登录时跳转
        http.exceptionHandling().authenticationEntryPoint(new CustomLoginUrlAuthenticationEntryPoint());
    }
}
